/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package org.suai.dao.impl;

import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.suai.dao.Buffer;
import org.suai.dao.Package;

/**
 *
 * @author awm
 */
public class BufferImpl implements Buffer {
    private Map buffer = new HashMap();

    public void setPackage(int userNumber, Package pkg) {
        Integer index = new Integer(userNumber);
        if(buffer.containsKey( index )) {
            List item = (List)buffer.get(index);
            item.add(pkg);
            buffer.put(index, item);
        } else {
            List listNew = new LinkedList();
            listNew.add(pkg);
            buffer.put(index, listNew);
        }
    }

    @Override
    public Package getPackage(int userNumber) {
        //throw new UnsupportedOperationException("Not supported yet.");
        Integer index = new Integer(userNumber);
         if(buffer.containsKey( index )) {
            List item = (List)buffer.get(index);
            return (Package)item.get(0);
        }

        return null;
    }

    
    public List getPackagesForService() {
        List result = new LinkedList();
        
        for(Object key : buffer.keySet().toArray()) {
            List item = (List)buffer.get(key);
            if(item != null && item.size() > 0) {


                result.add(item.get(0));
            }
        }

        return result;
    }

    public void servicePackage(int userNumber) {
        Integer index = new Integer(userNumber);
        if(buffer.containsKey( index )) {
            List item = (List)buffer.get(index);
            if(item != null && item.size() > 0) {
                item.remove(0);
            }
            buffer.put(index, item);
        } 
    }

    @Override
    public boolean isFree(int userNumber) {
       // return true;
        Integer index = new Integer(userNumber);
        if( !buffer.containsKey(index) || buffer.get(index) == null  || ((List)buffer.get(index)).size() == 0) {
            return true;
        }

        return false;
    }

    public String toString() {
       Integer countPackage = new Integer(0);
       
        for(Object key : buffer.keySet().toArray()) {
            List item = (List)buffer.get(key);
            if(item != null && item.size() > 0) {
                countPackage += item.size();
            }
        }
        
        return  countPackage.toString();

    }

}
